from fastapi import Query
from tortoise.expressions import Q
from datetime import datetime , timedelta

from app.controllers.goods.goods import goods_controller
from app.controllers.marketing.coupons import coupons_controller
from app.controllers.marketing.deposit import deposit_controller
from app.controllers.marketing.integral import integral_controller
from app.controllers.orders.list import orders_list_controller
from app.core.crud import CRUDBase
from app.models import OrdersList, GoodsSku, Coupons
from app.models.marketing import Draw, DrawlRole, CouponsRole, Integral
from app.schemas.marketing import DrawCreate, DrawUpdate, DepositCreate, CouponsCreate, IntegralCreate
import random

from app.schemas.orders import OrdersListCreate, OrdersListCreateMini


class DrawController(CRUDBase[Draw, DrawCreate, DrawUpdate]):
    def __init__(self):
        super().__init__(model=Draw)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: DrawCreate):
        ret = await self.create(obj_in=obj_in)
        return ret

    async def do_update(self, obj_in: DrawUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        if obj_in.status==1:
            print("开始兑奖")
            draw_id = obj_in.draw_id
            draw_rule = await DrawlRole.filter(id=draw_id).first().values()
            if draw_rule["type"] == 2:
                print(f"如果是优惠券{obj_in.user_id}直接设置用掉{draw_rule["type_id"]}")
                ##如果是优惠券直接设置用掉
                await Coupons.filter(user_id=obj_in.user_id,come_type=3,coupons_id=draw_rule["type_id"]).update(is_used=1)
            if draw_rule["type"] == 4:
                print(f"积分")
                await Coupons.filter(user_id=obj_in.user_id,come_type=3,coupons_id=draw_rule["type_id"]).update(is_used=1)
                data_in = IntegralCreate(
                    user_id =obj_in.user_id,
                    price =draw_rule['type_id'],
                    direction=1,
                    type=4,
                    type_id=obj_in.order_id,
                    expire_at=None,
                    remark='抽奖积分',
                )
                await integral_controller.do_create(obj_in=data_in)
        return True

    async def do_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True

    async def do_draw(self, user_id: int, order_id: int,space_id:int = Query(0, description="门店id"),):
        prizes = await DrawlRole.all().values()
        draw_dict = {draw['id']: draw for draw in prizes}
        ids = [prize["id"] for prize in prizes]  # 奖项名称id列表
        weights = [prize["role"] for prize in prizes]  # 对应的概率列表（权重）
        # 使用 random.choices 进行加权抽奖
        chosen_prize = random.choices(ids, weights=weights, k=1)[0]  ##奖品id
        prize = draw_dict[chosen_prize]  ##奖品
        ##设置中奖关联
        prize_id = prize['id']
        prize_type = prize['type']
        prize_type_id = prize['type_id']
        # 插入中奖记录
        status = 0 if prize_type ==3 else 1

        draw_log_data = DrawCreate(user_id=user_id, draw_id=prize_id, is_got=1, order_id=0, status=status,space_id=space_id)
        draw_log = await self.do_create(draw_log_data)
        if prize_type == 1:  # 折扣
            order = await OrdersList.filter(id=order_id).first().values()
            if prize_type_id == 0:  ##免单
                order["sale_roles"] = [{"rule": f"抽奖免单,记录id:{draw_log.id}"}]
                await orders_list_controller.order_refund(order_id=order_id,order_status=4)
                await OrdersList.filter(id=order_id).update(price=0.00, sale_price=order['price'],sale_roles=order['sale_roles'],status=1,is_give=1)
            elif prize_type_id>0: ##折扣
                order["sale_roles"] = [{"rule": f"抽奖{prize_type_id}折,记录id:{draw_log.id}"}]
                price = order['price']*prize_type_id/100
                sale_price = order['price']-price
                await OrdersList.filter(id=order_id).update(price=price, sale_price=sale_price,sale_roles=order['sale_roles'])
                ##sale_price通过充值金返回
                deposit_data = DepositCreate(
                    user_id=user_id,
                    price=float(sale_price),
                    direction=1,
                    goods_id=0,
                    goods_num=0,
                    remark=f"抽奖{prize_type_id}折赠送",
                    zs_price=0.00
                )
                await deposit_controller.do_create(obj_in=deposit_data)
        elif prize_type == 2:  # 优惠券
            # 获得优惠券
            coupons = await CouponsRole.filter(id=prize_type_id, state=1).first().values()
            if coupons:
                expire_at = coupons['expire_at']
                # 计算过期时间
                current_time = datetime.now()
                new_time = current_time + timedelta(days=expire_at)
                new_time_str = new_time.strftime("%Y-%m-%d %H:%M:%S")
                coupons_data = CouponsCreate(
                    user_id=user_id,
                    coupons_id=coupons['id'],
                    coupons_price=coupons['value'],
                    expire_at=new_time_str,
                    is_used=0,
                    come_type=3,
                    add_order_id=0,
                    order_goods_id=0,
                    remark=f"抽奖赠送,记录id:{draw_log.id}"
                )
                print(coupons_data,111)
                await coupons_controller.do_create(obj_in=coupons_data)
        elif prize_type == 3:  # 实物
            # order = await OrdersList.filter(id=order_id).first().values()
            goods = await goods_controller.do_detail(data_id=prize_type_id)
            sku_id = await GoodsSku.filter(goods_id=goods['id']).first().values("id")
            order_in = OrdersListCreateMini(
                type = goods["type"],
                sku = [{"sku_id":sku_id['id'],"num":1}]
            )
            ret = await orders_list_controller.do_create(obj_in=order_in,user_id=user_id)
            ##设置完成和赠送
            if ret["pay_status"]==1:
                sale_roles = [{"rule": f"抽奖赠送,记录id:{draw_log.id}"}]
                await orders_list_controller.order_success(out_trade_no=0,order_id=ret["order_id"])
                await OrdersList.filter(id=ret["order_id"]).update(price=0.00,sale_roles=sale_roles, is_give=1)
        elif prize_type == 4:  # 积分
            data_in = IntegralCreate(
                user_id=user_id,
                price=prize_type_id,
                direction=1,
                type=4,
                type_id=0,
                expire_at=None,
                remark='抽奖积分',
            )
            await integral_controller.do_create(obj_in=data_in)
        ##设置订单的抽奖状态
        # await OrdersList.filter(id=order_id).update(is_draw=2, draw_id=draw_log.id)
        return prize

draw_controller =DrawController()
